;
cmedit.AttachmentEdit = (function($, window, document) {
	var thisContext;
	var topUtil;  //顶层工具类
	var loadRange=0;
	var captionData={
			taskCode:"",
			subtitleFilePath:""
		};
	var numFlag=0;
	var AttachmentEditClass = function(){
    	
    }
	AttachmentEditClass.prototype = {
		/**
		 * 初始化
		 */
		init : function(){
			thisContext = this;
			topUtil = window.parent.cmedit.global;
			thisContext.initEvent();
		},
		
		/**
		 * 事件初始化
		 */
		initEvent : function(){
			$("#setAsLitimg").off('click').on('click',function(){
        		thisContext.setAsLitimg();
        	});
        	
        	$("#useGif").off('click').on('click',function(){
        		thisContext.useGif();
        	});
        	
        	$('#shotBtn').off('click').on('click',function(){
                thisContext.shotPic();
            });
            
            $('#getGif').off('mousedown').on('mousedown',function(){
                thisContext.getGif();
            });
            
            $('#batchInsert').off('click').on('click',function(){
            	thisContext.batchInsert(1);
            });
            
            $('#startTime').off('change').on('change',function(){
            	thisContext.showDuration();
            });
            
            $('#endTime').off('change').on('change',function(){
            	thisContext.showDuration();
            });
            
            $('#setInTime').off('click').on('click',function(){
            	thisContext.setInTime();
            });
            
            $('#setOutTime').off('click').on('click',function(){
            	thisContext.setOutTime();
            });
            // 字幕-start-----
			$('.captionPoint .startTime').off('change').on('change',function(){
            	thisContext.showCaptionDuration();
            });
            
            $('.captionPoint .endTime').off('change').on('change',function(){
            	thisContext.showCaptionDuration();
            });
            $('.captionPoint #intoPoint').off('click').on('click',function(){
            	thisContext.intoPoint();
            });
            
            $('.captionPoint #outPoint').off('click').on('click',function(){
            	thisContext.outPoint();
			});
			
			$(".resolveImgTitle .arrow").off("click").on("click",function(){
				if($(this).hasClass("arrowup")){
					$(this).removeClass("arrowup").addClass("arrowdown");
					$(".second .resolveImgContainer").fadeOut();
				}else{
					$(this).removeClass("arrowdown").addClass("arrowup");
					$(".second .resolveImgContainer").fadeIn();
				}
			});
			// 字幕-end----
            $('#downloadGif').off('click').on('click',function(){
            	var url = "a";
            	var fileName = "b";
            	thisContext.downloadGif(url,fileName);
            });
            
            $('#gifWidth').off('input').on('input',function(){
            	if($('#holdStyle').is(':checked') && $('#gifWidth').val() != '') {
            	    var gifHeight = parseInt($('#gifWidth').val())/2;
            	    gifHeight = thisContext.decimal(gifHeight,0);
            	    $('#gifHeight').val(gifHeight);
            	}
            });
            
            $('#gifHeight').off('input').on('input',function(){
            	if($('#holdStyle').is(':checked') && $('#gifHeight').val() != '') {
            	    var gifWidth = parseInt($('#gifHeight').val()) * 2;
            	    $('#gifWidth').val(gifWidth);
            	}
            });
            
            $('.editClose').off('click').on('click',function(){
            	thisContext.resetAttachEdit();
            });
            
            $('#gifRate').off('blur').on('blur',function(){
            	thisContext.checkRate();
            });
            
            $('a[name="attachmentEditTab"]').on('shown.bs.tab', function (e) {
                // 获取已激活的标签页
                var activeTab = $(e.target).attr("id");
                var maFilePath = $("#attachment_maFilePath").val();
                // 渲染视频区域
                thisContext.editAttachment(maFilePath,'',2,activeTab);
            });
            
         // 生成分解图
            $('#GenerateImg').off('mousedown').on('mousedown',function(){
                thisContext.GenerateImg();
            });
		},
		
		/**
         * GIF设置展开关闭
         */
        gifSetting : function(open){
        	if($(open).find('.fa').hasClass('fa-angle-down')){
                $(open).find('.fa').removeClass('fa-angle-down');
                $(open).find('.fa').addClass('fa-angle-up');
                $('.gifSetting').hide();
                $('.detailSet').show();
            }else{
                $(open).find('.fa').removeClass('fa-angle-up');
                $(open).find('.fa').addClass('fa-angle-down');
                $('.detailSet').hide();
                $('.gifSetting').show();
            }
        },
        
        /**
         * 资源编辑
         */
        editAttachment : function(maFilePath,maFileName,maFileType,activeTab){
      	  //视频处理
          $("#attachment_maFilePath").val(maFilePath);
      	  var attachHtml = '';
      	  if(maFileType == 2){
      		  // 如果是截图，需要处理跨域问题
      		  if(activeTab == 'shotTab'){
      			attachHtml += '<video id="gifVideoPre" width="100%" height="100%" crossorigin="anonymous" src="' + maFilePath + '" controls="controls" preload="meta">'
	             +'</video>';
      		  }else if(activeTab == 'gifTab'){
      			attachHtml += '<video id="gifVideoPre" width="100%" height="100%" src="' + maFilePath + '" controls="controls" preload="meta">'
	             +'</video>'; 
      		  }else if(activeTab == "captionTab"){
				attachHtml += '<video id="captionVideoPre" width="100%" height="100%" src="' + maFilePath + '" controls="controls" preload="meta">'
				+'</video>'; 
			  }
      		  
      	  }else if(maFileType == 1){
      		  attachHtml += '<img id="imgPre" width="100%" height="100%" src="' + maFilePath + '"'
      		  				+'</img>';
      	  }
      	  if(activeTab == 'shotTab'){
      		 $("#attachPreview").html(attachHtml);
      	  }else if(activeTab == 'gifTab'){
      		 $("#gifVideo").html(attachHtml);
      	  }else if(activeTab == 'captionTab'){
			 $("#captionVideo").html(attachHtml);
		  }
      	  $('.editCont').css('display','block');
      /*	$("#gifTab").click();*/
        },
        
        /**
         * 截图
         */
        shotPic : function(){
      	  vedioshot.init({
      	    	SHOTBAR:"shotBar",
      	    	VIDEO:"gifVideoPre"
      	    });
      	  vedioshot.clickToShot();
        },
        /**
         * 截图选中
         */
        shotSelect : function(e){
      	  if($(e).hasClass('shotPicCheck')){
      		  $(e).removeClass('shotPicCheck');
      	  }else{
      		  $(e).addClass('shotPicCheck');
      	  }
      	  
        },
        
        /**
         * 批量插入选中的图片
         */
        batchInsert : function(type){
          var temp = /^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\’:+!]*([^<>\"\"])*$/;
      	  var imgArray = new Array();
      	 /* var pDataImg = {
        		filename : "",
        		 fileSrc : ""
        	  };*/
      	  var ue = UE.getEditor("editer_");
      	  $('.shotPicCheck').each(function(i,item){
      		var imgsrc = $(this).find('[name="selectPic"]')[0].src;
      		var timestamp = $(this).next().text();
      		//检查是流媒体路径还是base64
      		if(!temp.test(imgsrc)){
          		var imgStr = imgsrc.substring(22);
          		var imgObj = {
          				imgBase64:imgStr,
          				imgSuffix:"png",
          				fileName:timestamp
          		};
          		imgArray.push(imgObj);
      		}else{
      			if(type == 1 || type == "1"){
      				var insertHtml = '<img src="'
 				       + imgsrc
	    			       + '"  width="600px" heigth="600px" alt="'
	    			       + timestamp +'"></img>';
      				ue.execCommand('insertHtml', insertHtml);
      			}else if(type == 2 || type == "2"){
      				$(".upLoadBtn").hide();
                	var imgHtml = '<img  src="' + imgsrc + '">'
    							+ '<div class="upLoadEdit">'
    							+ '<i class="iconfont icon-bianji" onclick="cmedit.EditSystem.uploadLitimgByCFB()"></i>'
    							+ '<i class="iconfont icon-shanchu5" onclick="cmedit.EditSystem.deleteLitimg()"></i>'
    							+ '</div>';
                	$(".uploadImg").html(imgHtml);
                	$(".uploadImg").show();
                	$("#litimgAddr").val(imgsrc);
    			    $("#shotPicLitimg").html('<img src="' + imgsrc + '">');
      			}
      		}
        	
      	  });
      	  if(imgArray.length > 0){
      		var mainGuid = $("#mainGuid").val();
      		numFlag=0;
      		thisContext.suolueTimer={};
      		//缩略图-批量插入定时器
			if(thisContext.suolueTimer){
				for(key in thisContext.suolueTimer){
					clearInterval(thisContext.suolueTimer[key])
				}
			}
      		imgArray.forEach(function(val,index,arr){
      			var postArr=[];
      			postArr.push(val);
      			var postData = {
      					 mainGuid : mainGuid,
     	        		 type :type,
     	        		 images : postArr
      	        };
        	  
        	  /**
        	   * 将截图保存到资源库
        	   */
        	  topUtil.ajaxRequest({
        			async: true,
        			url: cmedit.global.cmsPath + "UploadController/uploadImage",
        			type: 'POST',
        			data : JSON.stringify(postData),
          			dataType : 'json',
          			contentType: "application/json;charset=UTF-8",
        			success: function (data) {
        				if(data.status==true||data.status=="true"){
        					numFlag++;
          					var suolueTimer="suolueTimer"+numFlag;
//          					(function(suolueTimer){
          					thisContext.suolueTimer[suolueTimer] =setInterval(function(){
	    							var taskCode="";
	    							thisContext.ajaxByTimerNew(taskCode,data.data,type,suolueTimer);
	    					},1000)	
        					//插入操作
        				/*	var appendHtml = '';
        					var imgList = data.data;
        					if(type == 1 || type == "1"){
            					
            					for(var i = 0;i < imgList.length;i++){
            						appendHtml += '<img src="'
        		    				+ imgList[i].streamPath
        		    				+ '"width="600px" heigth="600px" alt="'
        		    				+imgList[i].fileName +'"></img>';
            						$("#" + imgList[i].fileName.split(".")[0]).attr('src',imgList[i].streamPath);
            					}
            					//setTimeout(function(){
            						ue.execCommand('insertHtml', appendHtml);
    		                	//	$("#shotPicLitimg").html('<img src="' + imgList[0].streamPath + '">');
          						//},1000);
            					
            					//设置为缩略图操作
        					}else if (type == 2 || type == "2"){
        						//$("#" + imgList[0].fileName).attr('src',imgList[0].streamPath);
        						$("#litimgPriview").attr('src',imgList[0].streamPath);
        		            	$("#litimgAddr").val(imgList[0].streamPath);
        		            	$("#shotPicLitimg").html('<img src="' + imgList[0].streamPath + '">');
        		            	
        		            	
        		            	$(".upLoadBtn").hide();
    		                	var imgHtml = '<img  src="' + imgList.streamPath + '">'
    	        							+ '<div class="upLoadEdit">'
    	        							+ '<i class="iconfont icon-bianji" onclick="cmedit.EditSystem.uploadLitimgByCFB()"></i>'
    	        							+ '<i class="iconfont icon-shanchu5" onclick="cmedit.EditSystem.deleteLitimg()"></i>'
    	        							+ '</div>';
    		                	$(".uploadImg").html(imgHtml);
    		                	$(".uploadImg").show();
    		                	$("#litimgAddr").val(imgList[0].streamPath);
    		                	//setTimeout(function(){
    		                	$("#shotPicLitimg").html('<img src="' + imgList[0].streamPath + '">');
    		                	$("#" + imgList[0].fileName.split(".")[0]).attr('src',imgList[0].streamPath);
          						//},4000);
    		                	//$("#shotPicLitimg").html('<img src="' + imgList[0].streamPath + '">');
        					}
        					cmedit.EditSystem.initAttachment();
        				}else{
        					alert(data.msg);
        				}*/
        				}else{
          					alert(data.msg);
          				}
        			}
        		});
        	  })
      	  }
      	  
        },
        
        
        
        /**
         * 删除截图
         * @param e
         */
        deleteShotPic : function(e){
      	  $(e).parent().parent().parent().remove();
        },
        
        /**
         * 立即生成gif
         */
        getGif : function(){
          var checkFlag = true;
          var markInTime = $("#inTime").val() == ""? 0 : parseFloat($("#inTime").val());
          markInTime = parseInt(markInTime * 1000);
    	  var markOutTime = $("#outTime").val() == "" ? 0 : parseFloat($("#outTime").val());
    	  markOutTime = parseInt(markOutTime * 1000);
      	  var videoUrl = $("#gifVideoPre").attr('src');
      	  var standardRate = $('#gifRate').val();
      	  var index = videoUrl.lastIndexOf("\/");
      	  var srcFileName = videoUrl.substring(index + 1, videoUrl.length);
      	  var srcFilePath = videoUrl.substring(0, index);
      	  if(!$("#gifWidth").val()){
      		  $.notify('gif宽度不能为空');
      		  return;
      	  }
      	  if(!$("#gifHeight").val()){
    		  $.notify('gif高度不能为空');
    		  return;
    	  }
      	  var cxSzie = $("#gifWidth").val();
      	  var cySize = $("#gifHeight").val();
      	  if(markInTime >= markOutTime){
      		  $.notify("入点时间大于或等于出点时间，请重新设置");
      		  return;
      	  }
      	  /**
      	   * 检查帧率
      	   */
      	  if(!thisContext.checkRate()){
      		  return;
      	  }
  		var postData = {
  				 serverCode : "dywebpageserver",
     			 srcFileName : srcFileName,
     			 srcFilePath : srcFilePath,
     			 markInTime : markInTime,
     			 markOutTime : markOutTime,
     			 standardRate : standardRate,
     			 cxSzie : cxSzie,
     			 cySize : cySize
     	  }
  			$('#getGif').attr('disabled','disabled');
     	  topUtil.ajaxRequest({
     		type: 'post',
   			async: true,
   			url: cmedit.global.cmsPath + "UploadController/videoToGif",
   			data : postData,
   			dataType : 'json',
   			success: function (data) {
   				if(data.status==true||data.status=="true"){
   					$('.gifLoadding').css('display','block');
   			      	$('.detailSet').css('display','none');
   			      	$('#gifPic').css('display','none');
   			      	$("#settingUpdown").removeAttr('onclick');
   					thisContext.shotLoading();
   					thisContext.getTransCodeStatus(data.data.taskCode,data.data.fileSizeCode,data.data.fileAddress,data.data.filePath);
   				}else{
   					$.notify(data.msg);
   					$('#getGif').attr('disabled',false);
   				}
   			}
   		});
      	  
        },
        
      /*  setTimeAllGifPic : function(gifPic,fileAddress){
        	$('#'+gifPic).attr('src',fileAddress);
        },
        setTimeAllGifFileSize : function(gifFileSize,fileAddress){
        	$('#'+gifFileSize).html(fileAddress)
        },*/
        
        /**
         * 获取转码任务状态
         */
        getTransCodeStatus : function(taskCode,fileSizeCode,fileAddress,filePath){
      	  var postData = {
      			  taskCode : taskCode,
      			  fileSizeCode : fileSizeCode,
      			  filePath : filePath,
      			fileAddress:fileAddress
      	  };
      	  
      	  topUtil.ajaxRequest({
        		type: 'post',
      			async: false,
      			url: cmedit.global.cmsPath + "UploadController/getTransCodeStatus",
      			data : postData,
      			dataType : 'json',
      			success: function (data) {
      				if(data.status==true||data.status=="true"){
      					if(data.data.tansStatus == "0"){
      						if(data.data.imgExist=="0"){
      							clearTimeout();
      							thisContext.continueLoading();
      							/*setTimeout($('#gifPic').attr('src',fileAddress),1000);
      							setTimeout($('#gifFileSize').html(data.data.gifFileSize),1000);*/
      							setTimeout(function(){
      								$('#gifPic').attr('src',fileAddress);
      								$('#gifFileSize').html(data.data.gifFileSize);
      							},5000);
      							/*setTimeout(setTimeAllGifPic(gifPic,fileAddress),3000);
      							setTimeout(setTimeAllGifFileSize(gifFileSize,data.data.gifFileSize),3000);*/
      						}else{
      							setTimeout('cmedit.AttachmentEdit.getTransCodeStatus("' + taskCode + '","' + fileSizeCode + '","' + fileAddress + '","' + filePath + '")',10000);
      						}
      					}else if(data.data.tansStatus == "1"){
      						$.notify("转码失败");
      						clearTimeout();
      						loadRange = 0;
      						$('.gifLoadding').css('display','none');
      			        	$('.detailSet').css('display','block');
      			        	$('#getGif').removeAttr('disabled');
      			        	$("#settingUpdown").attr('onclick','cmedit.AttachmentEdit.gifSetting(this)');
      					}else if(data.data.tansStatus == "-1"){
      						setTimeout('cmedit.AttachmentEdit.getTransCodeStatus("' + taskCode + '","' + fileSizeCode + '","' + fileAddress + '","' + filePath + '")',10000);
      					}
      				}else{
      					alert(data.msg);
      					setTimeout('cmedit.AttachmentEdit.getTransCodeStatus("' + taskCode + '","' + fileSizeCode + '","' + fileAddress + '","' + filePath + '")',10000);
      				}
      			}
      		});
      	  
      	  
        },
        
        /**
         * 保存gif
         */
        useGif : function(){
      	  var attachType = 1;
      	  var resourceId = "";
      	  var resourceAddr = $("#gifPic").attr('src');
      	  if(resourceAddr == "../../static/images/pq.jpg"){
      		  $.notify("未生成gif，不能插入");
      		  return;
      	  }else{
      		  var resourceName = (new Date()).valueOf();
	    	  var fileRate = 3;
	    	  var appendHtml = "";
	    	  cmedit.EditSystem.uploadAttachment(attachType, resourceId, resourceAddr,resourceName, fileRate);
	    	  var ue = UE.getEditor("editer_");
				appendHtml += '<img src="'
				+ resourceAddr
				+ '" alt="'
				+resourceName +'"></img>';
				ue.execCommand('insertHtml', appendHtml);
      	  }
        },
        
        /**
         * 将截图保存为缩略图
         */
        setAsLitimg : function(){
      	  var selectNums = $('.shotPicCheck').length;
      	  if(selectNums < 1){
      		  alert("请选择一个截图");
      	  }else if(selectNums > 1){
      		  alert("只能选择一个截图作为缩略图")
      	  }else{
      		  thisContext.batchInsert(2);
      	  }
        },
        
        /**
         * 加载进度条动画
         */
        shotLoading : function(){
    		if(loadRange>98){
    			return false;
    		}else if(loadRange<=98){
    			setTimeout("cmedit.AttachmentEdit.shotLoading()",200);
    			$(".loadRange").css("width",loadRange+"%");
    			$('.rangeVal').html(loadRange+'%');
    			loadRange++;
    		}
    	},
    	
    	/**
    	 * 显示时间
    	 */
    	showDuration : function(){
    		var markInTime = $("#inTime").val() == ""? 0 : parseFloat($("#inTime").val());
    		var markOutTime = $("#outTime").val() == "" ? 0 : parseFloat($("#outTime").val());
        	var duration = thisContext.formatFloat(markOutTime - markInTime,1);
        	if(duration < 0){
        		duration = 0;
        	}
        	$("#durationTime").html(duration);
    	},
    	
    	/**
    	 * 防止精度丢失
    	 * @param f
    	 * @param digit
    	 * @returns {Number}
    	 */
    	formatFloat : function (f, digit) {
    	    var m = Math.pow(100, digit);
    	    return Math.round(f * m, 100) / m;
    	},
    	
    	continueLoading : function(){
    		if(loadRange>100){
    			$.notify('加载完成');
    			loadRange = 0;
    			$('#getGif').removeAttr('disabled');
    			$('.gifLoadding').css('display','none');
    			$('.detailSet').css('display','block');
    			$("#settingUpdown").attr('onclick','cmedit.AttachmentEdit.gifSetting(this)');
    			$('#settingUpdown').click();
    			$('#gifPic').css('display','block');
    			return false;
    		}else if(loadRange<=100){
    			setTimeout("cmedit.AttachmentEdit.continueLoading()",20);
    			$(".loadRange").css("width",loadRange+"%");
    			$('.rangeVal').html(loadRange+'%');
    			loadRange++;
    		}
    	},
    	
    	/**
    	 * 下载gif
    	 */
    	downloadGif : function(){
    		var url = $("#gifPic")[0].src; ;
    	    var fileName = (new Date()).valueOf() + ".gif";
    		if(typeof url == 'object' && url instanceof Blob)
    	    {
    	        url = URL.createObjectURL(url); // 创建blob地址
    	    }
    	    var aLink = document.createElement('a');
    	    aLink.href = url;
    	    aLink.download = fileName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
    	    var event;
    	    if(window.MouseEvent) event = new MouseEvent('click');
    	    else
    	    {
    	        event = document.createEvent('MouseEvents');
    	        event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    	    }
    	    aLink.dispatchEvent(event);
    	},
    	/**
    	 * 设置入点
    	 */
    	setInTime : function(){
    		var video = $('#gifVideo #gifVideoPre');
    		var maxduration = video[0].duration;
    		var currentTime = video[0].currentTime;
    		$("#inTime").val(currentTime);
    		var inTime = thisContext.getTime(currentTime);
    		$("#startTime").html(inTime);
    		thisContext.showDuration();
    	},
    	
    	/**
    	 * 设置出点
    	 */
    	setOutTime : function(){
    		var video = $('#gifVideo #gifVideoPre');
    		var maxduration = video[0].duration;
    		var currentTime = video[0].currentTime;
    		$("#outTime").val(currentTime);
    		var outTime = thisContext.getTime(currentTime);
    		$("#endTime").html(outTime);
    		thisContext.showDuration();
    	},
    	
    	/**
    	 * 检查帧数是否在范围内
    	 */
    	checkRate : function(){
    		var reg = /^([5-9]|10)$/;
    		var flag =  reg.test(parseInt($("#gifRate").val()));
    		if(!flag){
        		$.notify("帧率只能输入5-10之间的整数！");
        		$('#gifRate').val(5);
        	}
    		return flag;
    	},
	    /**
	  	 * 图片刷新
	  	 */
	  	reFlush : function(e){
	  		var id=e.id;
	  		var src=e.src;
	  		if(src.substr(0,7).toLowerCase() == "http://"){
	  			var url=src+"?s="+ (new Date()).getTime();
	  			$("#"+id).attr("src",url); 
	  		}
	  	},
    	/**
    	 * 将帧数转换为时分秒
    	 */
    	getTime : function(currentTime){
    		var MOVIESCALE = 1;
    		var fps = 25;
    		var hour = (currentTime / (MOVIESCALE * 3600));
    		var dwReste = currentTime % (MOVIESCALE * 3600);

    		var minute = (dwReste / (MOVIESCALE * 60));
    		var dwReste = (dwReste % (MOVIESCALE * 60));

    		var second = dwReste / MOVIESCALE;
    		var dwReste = (dwReste % MOVIESCALE);

    		var minsec = dwReste * fps;

    		var sh = Math.floor(hour) >= 10 ? Math.floor(hour) : "0" + Math.floor(hour);
    		var sm = Math.floor(minute) >= 10 ? Math.floor(minute) : "0"
    				+ Math.floor(minute);
    		var ss = Math.floor(second) >= 10 ? Math.floor(second) : "0"
    				+ Math.floor(second);
    		var sf = Math.ceil(minsec) >= 10 ? Math.ceil(minsec) : "0"
    				+ Math.ceil(minsec);
    		if (sf == 25) {
    			ss = Number(ss) + 1;
    		}
    		if (ss == 60) {
    			sm = Number(sm) + 1;
    		}
    		if (sm == 60) {
    			sh = Number(sh) + 1;
    		}
    		//展示到毫秒
    		/*return sh + ":" + (sm == 60 ? "00" : sm) + ":" + (ss == 60 ? "00" : ss)
    				+ ":" + (sf == 25 ? "00" : sf);*/
    		
    		//展示到秒
    		return sh + ":" + (sm == 60 ? "00" : sm) + ":" + (ss == 60 ? "00" : ss);

    	},
    	
    	/**
    	 * 处理小数位数
    	 */
    	decimal : function(num,v){
    		var vv = Math.pow(10,v);
    		return Math.round(num*vv)/vv;
    	},
    		
    	/**
    	 * 重置编辑区
    	 */
    	resetAttachEdit : function(){
    		$("#shotTab").click();
    		//$("#gifTab").click();
    		$('.editCont').css('display','none');
    		$("#attachPreview #gitVideoPre").remove();
    		$("#attachPreview").html('');
    		$("#gifVideo #gitVideoPre").remove();
        	$("#gifVideo").html('');
        	$('#inTime').val('');
        	$('#startTime').html('00:00:00');
        	$('#outTime').val('');
        	$('#endTime').html('00:00:00');
        	$('#gifWidth').val('320');
        	$('#gifHeight').val('160');
        	$('#gifRate').val('5');
        	$("#shotBar>li").not(":eq(0)").remove();
        	// 字幕的值重置
			if(thisContext.generateTimer){
				clearInterval(thisContext.generateTimer);
			}
			if(thisContext.subtitleTimer){
				clearInterval(thisContext.subtitleTimer);
			}
			//缩略图-批量插入定时器
		
			if(thisContext.suolueTimer){
				for(key in thisContext.suolueTimer){
					clearInterval(thisContext.suolueTimer[key])
				}
			}
			
			$(".captionPoint .startTime").html("00:00:00");
			$(".captionPoint .endTime").html("00:00:00");
			$(".captionPoint .duringTime").html("00分00秒");
			$("#inTimeCaption").val(0);
			$("#outTimeCaption").val(0);
			var defaultTitleone='<div class="defaultTitle">分解图预览</div>';
			$("#resoveImgOneTmpContainer").html(defaultTitleone);
			var defaultTitltwo='<div class="defaultTitle">字幕图预览</div>';
			$("#generateSubtitleImgTmpContainer").html(defaultTitltwo);
			cmedit.EditSystem.initAttachment();

    	},
    	
    	/**
         * GenerateImg生成分解图
         */
        GenerateImg : function(){
			if(thisContext.generateTimer){
				clearInterval(thisContext.generateTimer);
			}
			if(thisContext.subtitleTimer){
				clearInterval(thisContext.subtitleTimer);
			}
			var checkFlag = true;
			var markInTime = $("#inTimeCaption").val() == ""? 0 : parseFloat($("#inTimeCaption").val());
			markInTime = parseInt(markInTime * 1000);
			var markOutTime = $("#outTimeCaption").val() == "" ? 0 : parseFloat($("#outTimeCaption").val());
			markOutTime = parseInt(markOutTime * 1000);
			
			var videoUrl = $("#captionVideoPre").attr('src');
			var index = videoUrl.lastIndexOf("\/");
			var srcFileName = videoUrl.substring(index + 1, videoUrl.length);
			var srcFilePath = videoUrl.substring(0, index);
			if(markInTime >= markOutTime){
				$.notify("入点时间大于或等于出点时间，请重新设置");
				return;
			}
			var postData = {
				serverCode : "dywebpageserver",
				fileName : srcFileName,
				PathInfo : srcFilePath + "/",
				startTime : markInTime,
				endTime : markOutTime,
			}
			topUtil.ajaxRequest({
				type: 'post',
				async: false,
				// url: cmedit.global.releasePath + "/videoSubtitleController/videoSubtitleExtractTask",
				url: cmedit.global.cmsPath + "videoSubtitleController/videoSubtitleExtractTask",
				data : postData,
				dataType : 'json',
				success: function (data) {
					if(data.status==true||data.status=="true"){
						captionData.taskCode = data.data.taskCode;
						captionData.subtitleFilePath = data.data.subtitleFilePath;
						captionData.middlePath = data.data.middlePath;
						captionData.subtitleFilePath = data.data.subtitleFilePath;
						thisContext.generateTimer =	setInterval(function(){
							var taskCode = captionData.taskCode;
							thisContext.ajaxByTimer(captionData.taskCode,captionData.subtitleFilePath,captionData.middlePath)
						},1000)	 
					}else{
						$.notify(data.msg);
					}
				}
			});
        },
        
        ajaxByTimer: function(taskCode,subtitleFilePath,middlePath){
			var postData = {
				middlePath:middlePath,
				subtitleFilePath:subtitleFilePath,
				taskCode:taskCode
			}
			topUtil.ajaxRequest({
				type: 'post',
				async: false,
				url: cmedit.global.cmsPath + "videoSubtitleController/getSubtitleCodeStatus",
				data : postData,
				dataType : 'json',
				success: function (data) {
					if(data.status==true||data.status=="true"){
						if(data.data.tansStatus=="-1"){
							$.notify("正在生成分解图，请稍等");
						}
						if(data.data.tansStatus=="0" && data.data.imgIsExist!="0"){
							$.notify("转码已完成，未检测到字幕图！");
							clearInterval(thisContext.generateTimer);
						}
						if(data.data.tansStatus=="0" && data.data.imgIsExist=="0"){
							$.notify("转码已完成");
							clearInterval(thisContext.generateTimer);
							var resoveImgOneTmp=template('resoveImgOneTmp', data.data);
							$("#resoveImgOneTmpContainer").html(resoveImgOneTmp);
							// 拖拽；
							thisContext.initSortable();
						}
					}else{
						$.notify(data.msg);
						clearInterval(thisContext.generateTimer);
					}
				}
			});
	 	},
	 	ajaxByTimerNew: function(taskCode,data,type,suolueTimer){
	 		debugger;
	 		var ue = UE.getEditor("editer_");
			var postData = {
					type :type,
					data:JSON.stringify(data)
			}
			topUtil.ajaxRequest({
				type: 'post',
				async: false,
				url: cmedit.global.cmsPath + "UploadController/getSuoImgtatus",
				data : postData,
				dataType : 'json',
				success: function (data) {
//					clearInterval(thisContext.suolueTimer[suolueTimer]);
					if(data.data.length >0 && (data.status==true||data.status=="true")){
						//
						var imgList = data.data;
						var  taskCodeStatus=imgList[0].taskCodeStatus;
						if(imgList[0].taskCodeStatus=="0"){
							//console.log(captionData);
							var appendHtml = '';
          					if(type == 1 || type == "1"){
          						$.notify("正在插入图片，请稍等");
          						clearInterval(thisContext.suolueTimer[suolueTimer]);
//          						clearInterval(suolueTimer);
              					for(var i = 0;i < imgList.length;i++){
              						appendHtml += '<img id="'+imgList[i].fileName+'" cfbresourceid="'+imgList[i].fileName+'" src="'
          		    				+ imgList[i].streamPath
          		    				+ '"width="600px" heigth="600px" alt="'
          		    				+imgList[i].fileName +'" ></img>';
              					}
              					ue.execCommand('insertHtml', appendHtml);
              					for(var i = 0;i < imgList.length;i++){
              						$("#" + imgList[i].fileName.split(".")[0]).attr('src',imgList[i].streamPath);
              					}
              					//设置为缩略图操作
          					}else if (type == 2 || type == "2"){
          						$.notify("正在设为缩略图，请稍等");
          						clearInterval(thisContext.suolueTimer[suolueTimer]);
          						//$("#" + imgList[0].fileName).attr('src',imgList[0].streamPath);
          						$("#litimgPriview").attr('src',imgList[0].streamPath);
          		            /*	$("#litimgAddr").val(imgList[0].streamPath);
          		            	$("#shotPicLitimg").html('<img id="' + imgList[0].fileName + '" src="' + imgList[0].streamPath + '"  onclick="cmedit.AttachmentEdit.reFlush(this);">'); */         		            	
          		            	$(".upLoadBtn").hide();
      		                	var imgHtml = '<img  id="'+imgList[0].fileName+'" cfbresourceid="'+imgList[0].fileName+'" src="' + imgList[0].streamPath + '" >'
      	        							+ '<div class="upLoadEdit">'
      	        							+ '<i class="iconfont icon-bianji" onclick="cmedit.EditSystem.uploadLitimgByCFB()"></i>'
      	        							+ '<i class="iconfont icon-shanchu5" onclick="cmedit.EditSystem.deleteLitimg()"></i>'
      	        							+ '</div>';
      		                	$(".uploadImg").html(imgHtml);
      		                	$(".uploadImg").show();
      		                	$("#litimgAddr").val(imgList[0].streamPath);
          		                		//$("#imgNew").attr('src',imgList[0].streamPath);
      		                	$("#shotPicLitimg").html('<img id="' + imgList[0].fileName + '" src="' + imgList[0].streamPath + '"  onclick="cmedit.AttachmentEdit.reFlush(this);">');
          		               $("#" + imgList[0].fileName.split(".")[0]).attr('src',imgList[0].streamPath);
          					}
              				cmedit.EditSystem.initAttachment();
						}
					}else{
						$.notify(data.msg);
						clearInterval(thisContext.suolueTimer);
					}
				}
			});
	 	},
        
     // 生成字幕图
		generateSubtitles:	function(){
			var checkedImgs=[];
			var images=[];
			for (var i = 0; i < $(".resoveImgOne input[type=checkbox]:checked").length; i++) {
				var inputCheck = $(".resoveImgOne input[type=checkbox]:checked")[i];
                checkedImgs.push($(inputCheck).val());
			};
			checkedImgs.forEach(function(value,index,arr){
				var index = value.lastIndexOf("\/");
				var fileName = value.substring(index + 1, value.length);
				var pathInfo = value.substring(0, index);
				images.push({
					fileName:fileName,
					pathNew:pathInfo,
					pathInfo:captionData.subtitleFilePath,
					subtitleFilePath:captionData.subtitleFilePath
				})
			});

			postData = {
				serverCode : "dywebpageserver",
				images: JSON.stringify(images),
				width:$(".resoveImgOne").first().find("img")[0].naturalWidth,
				height:$(".resoveImgOne").first().find("img")[0].naturalHeight
			};


			topUtil.ajaxRequest({
				type: 'post',
				async: false,
				url: cmedit.global.cmsPath + "MergeSubtitleImageController/MergeSubtitleImageTask",
				data : postData,
				dataType : 'json',
				success: function (data) {
					if(data.status==true||data.status=="true"){
						// 字母图路径；
						captionData.subtitleImgSrc= data.data.middlePath+'/'+data.data.subtitleFileName;
						thisContext.subtitleTimer =	setInterval(function(){
							thisContext.ajaxBysubTitleTimer(data.data.taskCode)
						},1000)	
						return;
					
					}else{
						$.notify(data.msg);
					}
				}
			});

		},
		
		// 插入字幕图
		insertCaptonToUe:function(){
			var ue = UE.getEditor("editer_");
			if ($("#generateSubtitleImgTmpContainer img").length>0){
				var src = $("#generateSubtitleImgTmpContainer img").attr("src")
				var	captionTitleHtml = '<img src="'+src+'"  width="420" height="280" >';
			} else {
				$.notify("未生成字幕图，请先生成字幕图");
				return;
			}
			ue.execCommand('insertHtml', captionTitleHtml);
		},
		
		/**
    	 * 显示时间
    	 */
    	showCaptionDuration : function(){
    		var markInTime = $("#inTimeCaption").val() == ""? 0 : parseFloat($("#inTimeCaption").val());
    		var markOutTime = $("#outTimeCaption").val() == "" ? 0 : parseFloat($("#outTimeCaption").val());
			// var duration = thisContext.formatFloat(markOutTime - markInTime,1);
			var duration = parseInt(markOutTime - markInTime);
        	if(duration < 0){
        		duration = 0;
			}
			// 转化成分秒；
			duration=thisContext.sec_to_time(duration);
        	$(".captionPoint .duringTime").html(duration);
    	},
		sec_to_time: function (s) {
            var t="";
            if (s > -1) {
                var min = Math.floor(s / 60) % 60 + Math.floor(s / 60)
                var sec = s % 60;
                if (min < 10) { t += "0"; }
                t += min + "分";
                if (sec < 10) { t += "0"; }
                t += sec + "秒";
            }
			return t;
			
        },
     // ----------Caption----------------
    	/**
    	 * 设置入点
    	 */
    	intoPoint : function(){
    		var video = $('#captionVideoPre');
    		var maxduration = video[0].duration;
    		var currentTime = video[0].currentTime;
    		$("#inTimeCaption").val(currentTime);
    		var inTime = thisContext.getTime(currentTime);
    		$(".captionPoint .startTime").html(inTime);
    		thisContext.showCaptionDuration();
    	},
    	
    	/**
    	 * 设置出点
    	 */
    	outPoint : function(){
    		var video = $('#captionVideoPre');
    		var maxduration = video[0].duration;
    		var currentTime = video[0].currentTime;
    		$("#outTimeCaption").val(currentTime);
    		var outTime = thisContext.getTime(currentTime);
    		$('.captionPoint .endTime').html(outTime);
    		thisContext.showCaptionDuration();
    	},
		// 拖拽
		initSortable:function(){
			$( "#resoveImgOneTmpContainer" ).sortable({
				revert: true
			});
		},
		// 删除图片；
		deleteResoveImgOne:function(target){
			$(target).parent().parent().remove();
		},
	 
		ajaxBysubTitleTimer: function(taskCode){
			var postData = {
				taskCode:taskCode,
				middlePath:captionData.subtitleImgSrc
			}
			topUtil.ajaxRequest({
				type: 'post',
				async: false,
				url: cmedit.global.cmsPath + "MergeSubtitleImageController/getMergeSubtitleCodeStatus",
				data : postData,
				dataType : 'json',
				success: function (data) {
					if(data.status==true||data.status=="true"){
						if(data.data.tansStatus=="-1"){
							$.notify("正在生成字幕图，请稍等");
						}
						if(data.data.tansStatus=="0" && data.data.gifFileSize!="0"){
							$.notify("字幕图叠加任务结束，为查询到叠加图");
							clearInterval(thisContext.subtitleTimer);
						}
						if(data.data.tansStatus=="0" && data.data.gifFileSize=="0"){
							console.log(captionData);
							clearInterval(thisContext.subtitleTimer);
							var generateSubtitleImg='<img style="max-width:100%;width:auto;height:auto;" src="'+ captionData.subtitleImgSrc+'">';
							$("#generateSubtitleImgTmpContainer").html(generateSubtitleImg);
						}
					}else{
						$.notify(data.msg);
						clearInterval(thisContext.subtitleTimer);
					}
				}
			})
		},
		
		//下载字幕到本地 
		downLoadSbutitle:function(){

		},
		
        
		constructor : AttachmentEditClass,
	};
	
	return new AttachmentEditClass();
})(jQuery, window, document);
$(cmedit.AttachmentEdit.init());